package org.scau.studentevaluation.util;


import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.scau.studentevaluation.annotation.NotNullField;
import org.scau.studentevaluation.exception.FieldNullException;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: lyl
 * 用于检查空参数
 * 依赖mybatis
 */
@Service
public class FieldCheckUtil {
    // 该字段是否为空
    public boolean isNULL(String field,Object object){
        MetaObject metaObject = SystemMetaObject.forObject(object);
        Object value = metaObject.getValue(field);
        return value == null;
    }
    // 若是空抛出异常
    public void throwNULLServiceException(String field,Object object) throws FieldNullException {
        if (isNULL(field,object))throw new FieldNullException("缺少参数：["+field+"]");
    }
    public void throwNULLServiceException(List<String> field,Object object) throws FieldNullException{
        for (String f : field) {
            throwNULLServiceException(f, object);
        }
    }
    // 根据注解来判断
    public void throwNULLServiceException(Object object) throws FieldNullException{
        Class<?> aClass = object.getClass();
        NotNullField annotation = aClass.getAnnotation(NotNullField.class);
        if (annotation != null){
            // 所有字段都要检测
            MetaObject metaObject = SystemMetaObject.forObject(object);
            String[] getterNames = metaObject.getGetterNames();
            List<String> fields = new ArrayList<>();
            for (String getterName : getterNames) { fields.add(getterName); }
            throwNULLServiceException(fields,object);
        }else {
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                NotNullField annotation1 = declaredField.getAnnotation(NotNullField.class);
                if (annotation1 != null){
                    // 针对该字段进行检测
                    String name = declaredField.getName();
                    throwNULLServiceException(name,object);
                }
            }
        }
    }
    // 所有都不能为空
    public void throwNULLServiceExceptionALL(Object object) throws FieldNullException{
        MetaObject metaObject = SystemMetaObject.forObject(object);
        String[] getterNames = metaObject.getGetterNames();
        for (String getterName : getterNames) {
            throwNULLServiceException(getterName,object);
        }
    }

}
